package com.sumer.psychology.photo.application.command;

import com.sumer.psychology.common.Assert;
import com.sumer.psychology.photo.domain.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 照片服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/29
 * Time: 15:22
 */
@Transactional
public class PhotoApplicationService {
    private static Logger logger = LoggerFactory.getLogger(PhotoApplicationService.class);
    private PhotoRepository photoRepository;

    public PhotoApplicationService(PhotoRepository photoRepository) {
        this.photoRepository = photoRepository;
    }

    /**
     * 上传照片
     *
     * @param uploadPhotoCommand command
     */
    public PhotoId upload(UploadPhotoCommand uploadPhotoCommand) {
        Photo newPhoto = new Photo(
                photoRepository.nextIdentity(),
                uploadPhotoCommand.title(),
                uploadPhotoCommand.description(),
                uploadPhotoCommand.fileId(),
                new AlbumId(uploadPhotoCommand.albumId()),
                uploadPhotoCommand.author());

        photoRepository().add(newPhoto);

        return newPhoto.photoId();
    }

    /**
     * 编辑照片
     *
     * @param changePhotoCommand command
     */
    public void change(ChangePhotoCommand changePhotoCommand) {
        Photo aPhoto = photoRepository().ofPhotoId(
                new PhotoId(changePhotoCommand.photoId()));
        Assert.notNull(aPhoto, "照片为空");

        aPhoto.changeTitleAndDescription( // 改变照片标题和描述
                changePhotoCommand.title(),
                changePhotoCommand.description());

        aPhoto.assignInto( // 改变照片归属的相册
                new AlbumId(changePhotoCommand.albumId()));
    }

    /**
     * 删除照片
     *
     * @param deletePhotoCommand command
     */
    public void delete(DeletePhotoCommand deletePhotoCommand) {
        Photo aPhoto = photoRepository().ofPhotoId(
                new PhotoId(deletePhotoCommand.photoId()));

        if (aPhoto != null) {
            aPhoto.delete();
        }

    }

    /**
     * 删除相册下的照片
     *
     * @param deletePhotosCommand command
     */
    public void deleteAllOfAlbum(DeletePhotosCommand deletePhotosCommand) {
        List<Photo> allPhotosOfAlbum = photoRepository().ofAlbumId(
                new AlbumId(deletePhotosCommand.albumId()));

        if (CollectionUtils.isNotEmpty(allPhotosOfAlbum)) {
            logger.info("{}相册下有{}张照片待删除",
                    deletePhotosCommand.albumId(),
                    allPhotosOfAlbum.size());

            for (Photo photo : allPhotosOfAlbum) {
                photo.delete();
            }
        }
    }

    private PhotoRepository photoRepository() {
        return photoRepository;
    }

}
